package Server.ServerCore.Controller;

import Server.ServerCore.Model.dbsql.model.GameRole;
import Server.ServerCore.Repository.LoginServiceImpl;
import Server.ServerCore.Service.DataPacks.packRequest.Login_request;
import Server.ServerCore.Service.DataPacks.packRespose.Login_response;
import Server.ServerCore.Service.DataPacks.packRespose.RoleIniti_response;
import Server.ServerCore.Service.Logic.HandleController;


import Server.ServerCore.Model.Player.PlayerInstance;
import Server.ServerCore.Service.hardCode.SessionStatus;
import Server.ServerCore.Service.service.PlayerManagerService;


import Server.ServerCore.Service.Logic.RegisterPack;

import Server.ServerCore.Service.usyns.SingelTable;
import Server.ServerCore.Service.usyns.SingelTableManager;
import org.jboss.netty.buffer.ChannelBuffer;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.security.MessageDigest;


/**
* @author :石头哥哥 <br/>
*         Date: 12-12-9<br/>
*         Time: 下午8:32<br/>
*         connectMethod:13638363871@163.com<br/>
*         登陆处理
*
*         LoginController = 11
*
*/
@Service
public class LoginController extends HandleController {
    private static final long serialVersionUID = 2995492325154307817L;
    @Resource
    private LoginServiceImpl loginService;
    @Resource
    private SingelTableManager singelTableManager;
    @Override
    public void DispatchPack(ChannelBuffer buffer, PlayerInstance player) {
        /**
         * 1 成功 2.用户密码错误 3.服务器繁忙 4账 户冻结 5. 帐号在线中 6. 未知错误
         */
        Login_request loginRequest= (Login_request) parseObject(buffer,Login_request.class);

        int result=0; //玩家帐号状态
        int role_id = 0; //玩家编号
        Login_response loginResponse=new Login_response();
        PlayerInstance playerInstance = PlayerManagerService.getUserbyUserAccount(loginRequest.getAccount());
        if (playerInstance!=null){
            role_id = playerInstance.getID();
            result = 5;
            loginResponse.setResult(result);
            loginResponse.setRole_id(role_id);

        }else{//角色不在线，验证并 初始化角色信息
            GameRole gameRole=loginService.getGameAccountsByPassport(loginRequest.getAccount());
            //密码加密（简单的处理，密钥：key="game"）：MD5串明文：password+"game"
            if (gameRole != null&&MD5(gameRole.getRolePassword() + loginRequest.getKey()).equals(loginRequest.getPwd())) {
                    result = 1;// 成功
                    role_id = gameRole.getRid();
                    player.setID(role_id);
                    player.setUserAccount(loginRequest.getAccount());
                    player.setGameRole(gameRole);
                    player.setRole_Integration(gameRole.getRoleIntegration());//角色网站积分（购买筹码）
                    PlayerManagerService.userOnLine.put(role_id,player);
                    loginResponse.setResult(result);
                    loginResponse.setRole_id(role_id);
            }
            //验证通过 初始化角色
            if (result == 1) {
                    //修改角色初始化信息包 前后端还没有核对！！！！RoleGiftChip 网站活动赠送筹码记录
                    player.setBargainingChip(gameRole.getRoleBargainingChip());
                    RoleIniti_response roleInitiRespose=new RoleIniti_response();
                    roleInitiRespose.setRole_id(role_id);
                    roleInitiRespose.setRole_Balance(player.getBargainingChip());//角色筹码余额
                    roleInitiRespose.setRole_Integration(player.getRole_Integration());

                    player.setSessionStatus(SessionStatus.ONLINE);
                    /**
                     * 玩家适配牌桌信息
                     */
                    SingelTable singelTable=singelTableManager.getSingelTable();//某个玩家独占
                    singelTable.getGameCharacterFastList().add(player);//添加到玩家列表 此时列表中只有两个对象：0：bankerAI，1：player
                    player.setTableID(singelTable.getTableID());
                    player.setCircleUnitFastList(singelTable.getCircleUnitFastList());
                    player.DirectSend(roleInitiRespose.getJsonData(1,2));
            }

           }
        //登录 验证 回复包
        player.DirectSend(loginResponse.getJsonData(1,1));
    }

    @Override
    public void InitiController() {
        RegisterPack.GAME_CONTROLLERS[11]=this;
    }
    /**
     * MD5 加密方法 返回32位String
     *
     * @param text 需要加密的数据
     */
    private String MD5(String text) {
        StringBuffer md5 = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes());
            byte[] digest = md.digest();
            for (int i = 0; i < digest.length; i++) {
                md5.append(Character.forDigit((digest[i] & 0xF0) >> 0x4, 0x10));
                md5.append(Character.forDigit((digest[i] & 0xF), 0x10));
            }
        } catch (Exception e) {
        }
        return md5.toString();
    }


}
